import { BASE_URL } from '../static/config/index'

class Http {
  constructor(baseURL) {
    this.baseURL = baseURL
  }

  get(url, data) {
    return this.request('GET', url, data)
  }

  post(url, data) {
    return this.request('POST', url, data)
  }

  request(method, url, data) {
    return new Promise((resolve, reject) => {
      uni.request({
        method,
        url: this.baseURL + url,
        data,
        header: {
          'token': (uni.getStorageSync('userInfo')).token || ''
        },
        success: ({ data: res }) => {
          if (res.code == 200) {
            resolve(res)
          } else {
            if (res.code == 401) {
              uni.clearStorageSync()
              return uni.reLaunch({
                url: '/pages/login/index'
              })
            }

            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
            reject(res)
          }
        },
        fail: () => { },
        complete: () => { }
      })
    })
  }
}

const http = new Http(BASE_URL)

export default http
